//
//  TrainningStartController.swift
//  DaRings
//
//  Created by 魔样科技 on 2022/11/3.
//

import Foundation
import MYModule
import UIKit
import SwiftyTimer
import SwiftEntryKit

import RxCocoa
import RxSwift
import CRPSmartRing

open class TrainningStartController: ViewController {
    
    public var type: TrainingType = .unknown
    
    private(set) var wearStateHandle: ((_ state: Int) ->Void)?
    
    private var goalType: TrainingTypeContent = .unkown
    private var goal: Double = 0
    
    private var startTime: Int = 0
    
    open override func makeUI() {
        super.makeUI()
        
        startButton.backgroundColor = type.tintColor
        
        self.view.addSubview(self.startButton)
        self.startButton.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(140)
        }
        
        self.view.addSubview(self.goalSettingButton)
        self.goalSettingButton.snp.makeConstraints { make in
            make.height.equalTo(60)
            make.leading.equalTo(68)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-48)
        }
        
        self.navigation.bar.backgroundColor = UIColor.background
        self.navigation.item.title = type.title
        
        addNotifaction()
        
        weakState()

    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    /// 检测是否佩戴
    private func weakState(handle: ((_ state: Int) ->Void)? = nil) {
        self.wearStateHandle = handle
        BluetoothManager.shared.setWearStateChangeListener()
        
    }
    
    open func addNotifaction() {
        
        NotificationCenter.default.rx.notification(Notification.Name.kReceiveWearStateNotification).take(until: self.rx.deallocated).subscribe(onNext:{[weak self] notification in
            guard let self = self else { return }
            self.wearState(noti: notification)
        }).disposed(by: rx.disposeBag)
        
        
    }
    
    
    @objc open func wearState(noti: Notification) {
        
        
        if self.navigationController?.topViewController != self {
            return
        }
        
        guard let dict = noti.userInfo as? [String: Any], let state = dict["result"] as? Int else {
            return
        }
        
        // 未佩戴
//        if state == 0 {
//            self.showAlertForNoRing()
//        } else {
            self.wearStateHandle?(state)
//        }
        
    }
    
  
    private func showAlertForNoRing() {
        UIAlertController.showAlertOk(title: "dialog_training_not_wear_ring_title".language, message: "", in: self)
    }
    
    open override func bindViewModel() {
        super.bindViewModel()
        
        self.startButton.rx.tap.subscribe { [weak self] _ in
            guard let self = self else { return }
            self.startCountdown()
        }.disposed(by: rx.disposeBag)
        
        self.goalSettingButton.rx.tap.subscribe(onNext: { [weak self] in
            guard let `self` = self else { return }
            
            DispatchQueue.main.async {
                let vc = TrainingGoalSettingController()
                vc.type = self.type
                vc.delegate = self
                self.navigationController?.pushViewController(vc, animated: true)
            }
            
        }).disposed(by: rx.disposeBag)
    }
    
    /// 设备设置 运动模式
    open func setDiviceTrainingType() {
        
        guard let type = type.CPRTrainningType else { return }
        
        let trainingModel = saveGoal()
        
        BluetoothManager.shared.setTraining(state: type, type: goalType.goalType, goal: trainingModel.goal)
        
        
        
    }
    
    private func startCountdown() {
        
//        weakState {[weak self] state in
//
            setDiviceTrainingType()
            
            willTrainingStartAnimation()
            
            
//        }
        
    }
    
    private func willTrainingStartAnimation() {
        var attributes = EKAttributes.centerFloat
        attributes.entryBackground = .color(color: .standardContent)
        attributes.screenBackground = .color(color: EKColor(type.tintColor))
        //遮罩层触摸是忽略、转发到窗口还是退出
        attributes.screenInteraction = .forward
        attributes.entryInteraction = .forward
        attributes.entranceAnimation = .translation
        attributes.exitAnimation = .translation
        attributes.displayDuration = .infinity

        self.countdownView.backgroundColor = type.tintColor
        self.countdownView.animalLabel.backgroundColor = type.tintColor
        self.countdownView.animalLabel.textColor = UIColor.assist_FFFFFF
        let view = UIView()
        view.addSubview(self.countdownView)
        self.countdownView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(kScreenWidth)
            make.height.equalTo(kScreenWidth)
        }
        self.countdownView.setupConfig(0.9, fromValue: 2, toValue: 0.2, fontSize: 180)
        self.countdownView.returnDoneClosure {
            SwiftEntryKit.dismiss()
            DispatchQueue.main.async {
                
                let vc = InTrainingController()
                vc.type = self.type
                vc.goalType = self.goalType
                vc.startTime = self.startTime
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        Timer.after(0.2.second) {
            SwiftEntryKit.display(entry: self.countdownView, using: attributes)
        }
        Timer.after(0.3.second) {
            self.countdownView.start()
        }
        
    }
    
    
    //MARK: - lazy load -
    public lazy var startButton: Button = {
        let button = Button()
        button.setBackgroundImage(UIImage(named: "btn_start_n")?.setupImageTintColor(tintColor: type.tintColor), for: .normal)
//        button.titleEdgeInsets = UIEdgeInsets(top: -10, left: 0, bottom: 0, right: 0)
        button.setTitle("gps_training_start".language, for: .normal)
        button.titleLabel?.font = Fonts.systemFont(ofSize: 20)
        button.setTitleColor(UIColor.assist_FFFFFF, for: .normal)
        button.backgroundColor = UIColor.Training.theme
        button.cornerRadius = 70
        return button
    }()
    
    public lazy var goalSettingButton: Button = {
        let button = Button()
        button.setBackgroundImage(UIImage(named: "btn_start_n")?.setupImageTintColor(tintColor: type.tintColor), for: .normal)
//        button.titleEdgeInsets = UIEdgeInsets(top: -10, left: 0, bottom: 0, right: 0)
        button.setTitle("gps_training_goal_setting".language, for: .normal)
        button.titleLabel?.font = Fonts.systemFont(ofSize: 24)
        button.setTitleColor(UIColor.assist_A9A9A9, for: .normal)
        button.cornerRadius = 30
        button.layer.borderColor = UIColor.assist_D0D0D0.cgColor
        button.layer.borderWidth = 1.0
        return button
    }()
    
    private lazy var countdownView: CountdownAnimationView = {
        let view = CountdownAnimationView()
        return view
    }()
}

extension TrainningStartController: GoalSettingResponseDelegate {
    
    
    public func setGoal(type: TrainingTypeContent, index: Int, goal: Double) {
        
        self.goalType = type
        self.goal = goal
        
        startCountdown()
        
    }
    
    /// 保存设置到数据库
    public func saveGoal() ->TrainingModel {
        
        let model = TrainingModel.newTraining(type: type.rawValue)
        self.startTime = model.startTime
        model.goalType = goalType.goalType.rawValue
        
        model.type = type.rawValue
        
        switch goalType {
            
        case .unkown:
            
            model.goal = 0
            
        default:
            model.goal = Int(goal)
            break
            
        }
        
        model.updateData()
        
        return model
        
    }
    
   
    
    
    
    
}
